﻿using System.Collections.Generic;
using System.Collections.Specialized;
using System.Data.Common;

namespace FileMonitor.Configuration
{
    public class Utility
    {
        private static System.Text.RegularExpressions.Regex regex = new System.Text.RegularExpressions.Regex("(\\[)(?<name>[A-Za-z0-9_\\.\\-]+)((,|:){1}?)(?<value>[^\\[^\\]]+)(\\])");
        public static Dictionary<string,string> ParseDictionary(string paramString)
        {

            if (!string.IsNullOrEmpty(paramString))
            {
                Dictionary<string, string> dics = new Dictionary<string, string>();
               System.Text.RegularExpressions.MatchCollection matchs = regex.Matches(paramString);
               foreach (System.Text.RegularExpressions.Match match in matchs)
               {
                   dics.Add(match.Groups["name"].Value, match.Groups["value"].Value);
               }
               return dics;
            }
            else
                return null;
        }

        public static NameValueCollection ParseNameValueCollection(string paramString)
        {

            if (!string.IsNullOrEmpty(paramString))
            {
                NameValueCollection values = new NameValueCollection();
                System.Text.RegularExpressions.MatchCollection matchs = regex.Matches(paramString);
                foreach (System.Text.RegularExpressions.Match match in matchs)
                {
                    values.Add(match.Groups["name"].Value, match.Groups["value"].Value);
                }
                return values;
            }
            else
                return null;
        }

        private static string ConstructParamsString(DbParameterCollection inputParams, NameValueCollection values, string fixParams)
        {
            string retStr = "";
            foreach (string key in values.Keys)
            {
                string k = "@" + key;
                if (inputParams.Contains(k))
                {
                    string v = values[key];
                    string str = string.Format("{0}='{1}'", k, v);
                    retStr = retStr + str + ",";
                }
            }
            retStr = retStr.TrimEnd(",".ToCharArray());
            if (!string.IsNullOrEmpty(fixParams))
            {
                retStr = retStr + "," + fixParams;
            }
            return retStr;
        }

        private static string ParseNameValueCollectionToSqlParams(NameValueCollection values)
        {
            string retStr = "";
            foreach (string key in values.Keys)
            {
                string k = "@" + key;
                string v = values[key];
                string str = string.Format("{0}='{1}'", k, v);
                retStr = retStr + str + ",";
            }
            retStr = retStr.TrimEnd(",".ToCharArray());
            return retStr;

        }
   
    
    }
}
